var valHandle; //定时器
const app = getApp()
const quote = app.globalData.quote;
const tool = quote.tool
const innerAudioContext = app.globalData.innerAudioContext; //引入音频播放器
const mta = require('../../../../utils/mta_analysis.js'); //引入腾讯埋点文件
const api = quote.api;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scale: app.globalData.scale,
    stopSrc: true, //控制音频
    // animation: null,
    isShowGuidance: true,
    isBrang: app.globalData.isBrang,
    gameStatus: app.globalData.gameStatus,
    imgUrl: null,
    core: true,
    stepText: 60, //设置倒计时初始值
    img: true,
    word: true,
    icon_error: false,
    isShowEndTip: false, //弹窗
    matchSuccess: false, //匹配成功的状态
    matchFail: false, //匹配失败的状态
    backdrop: false, //黑色半透明背景
    backdrop2: false,
    boxArr: [],
    currentArr: [],
    clickArr: [], //
    istrue: false,
    numArr: [], //统计学习多少组 最大6组
    isClicking: false,
    over: false, //游戏结束
    ismaintwo: false,
    GramOneList: '',
    isListenEnd: true, //播放结束状态
    time: '', //游戏用时
    status: 1,//区别游戏失败还是退出游戏
    bac: false
  },
  id:1,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // tools.countDown(null,this.data.scale);
    let that = this
    mta.Page.init(); //初始化腾讯埋点
    that.endTip = this.selectComponent("#endTip");
    that.GramOneList()
    that.setData({
      imgUrl: app.globalData.imgUrl,
      gameStatus: app.globalData.gameStatus
    })
    // setTimeout(() => {
    //     var valHandlerss=that.clickStartBtn()
    //     this.setData({
    //         isShowGuidance: false,
    //     })
    // }, 2000)
  },
  onUnload: function () {
    console.log('页面卸载清除定时器')
    clearTimeout(this.data.valHandlers)
    clearInterval(this.data.valHandle)
    clearTimeout(this.data.valHandler)
    clearTimeout(this.data.valHandlerss)
  },
  //开始游戏
  beginGame: function () {
    var that = this
    that.setData({
      isShowGuidance: false,
    })
    var valHandlerss = that.clickStartBtn()
  },
  //连连看数据列表  
  GramOneList() {
    var that = this
    var dataDic = {
      //CourseId: options.CourseId,
      GameMark: 1,
      ModuleId: app.globalData.moduleId
    };
    api.methodBasicEnglish_GetGameData({
      dataDic,
      success: function (res) {
        console.log(res)
        var data = res.data.data.GameList
        data.forEach(item => {
          item.status = false,
            item.imageUrl = app.globalData.imgUrl + item.ImgUrl
        })
        that.setData({
          GramOneList: data
        })
        console.log(that.data.GramOneList)
      }
    })
  },
  //选择
  clickBox(e) {
    clearInterval(valHandler)
    console.log(e)
    //防止重复点击
    let that = this
    var img = e.currentTarget.dataset.img
    var word = e.currentTarget.dataset.word
    if (img == '' || word == '') {
      console.log('结束')
      return
    }
    var status = e.currentTarget.dataset.status
    var id = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index //下标
    let {
      clickArr
    } = this.data;

    // 当点击的是当前元素的时候，退出
    if (~clickArr.indexOf(index)) return;

    this.setData({
      clickArr: [
        ...this.data.clickArr,
        index,
      ]
    })
    var list = that.data.GramOneList
    list[index].status = true

    that.setData({
      statu: index,
    })
    that.data.boxArr.push(id)
    if (that.data.boxArr.length >= 2) {
      this.setData({
        clickArr: [],
      })
      console.log('开始匹配')
      var nary = that.data.boxArr.sort()
      for (var i = 0; i < that.data.boxArr.length; i++) {
        if (nary[i] == that.data.boxArr[i + 1]) {
          that.setData({
            isListenEnd: false,
            stopSrc: false,
            statu: '1000',
          })
          innerAudioContext.src = '/src/record/true1.mp3'
          innerAudioContext.play()
          innerAudioContext.onEnded((res) => {
            console.log('音频结束播放', res)
            that.setData({
              isListenEnd: true,
              stopSrc: true
            })
          })
          list.filter((item, index, list) => {
            if (item.Sord == id) {
              item.Word = '',
                item.imageUrl = ''
            }
          })

          that.data.numArr.push(1)
          that.setData({
            istrue: true,
            statu: '1000',
            GramOneList: that.data.GramOneList, //匹配成功更新数据
          })
          if (that.data.numArr.length == 6) {
            console.log('游戏通关240')
            var time = 60 - that.data.stepText
            var courseName = app.globalData.courseName
            var timeStr = '0~10'
            if (time > 0 && time <= 10) {
              timeStr = '0~10'
            } else if (time > 10 && time <= 15) {
              timeStr = '11~15'
            } else if (time > 15 && time <= 25) {
              timeStr = '16~25'
            } else if (time > 25 && time <= 30) {
              timeStr = '26~30'
            } else {
              timeStr = '30以上'
            }
            app.aldstat.sendEvent('通关时长', { 'duration': courseName + '-游戏1-通关时长-' + timeStr });
            mta.Event.stat("duration_statistics", { 'duration': courseName + '-游戏1-通关时长-' + timeStr });
            if (that.data.gameStatus.GameTwo == true) { //如果有下一个游戏
              that.setData({
                main: false,
                ismaintwo: true,
                time: time,
              })
            }  else { //如果为最后一个游戏，则进入下一个任务弹窗
              console.log('最后一个游戏')
              that.setData({
                main: true,
                bac: true,
              })
            }
          }
          var valHandler = setTimeout(function () {
            list.forEach(item => {
              item.status = false
              that.setData({
                GramOneList: list, //匹配成功更新数据
              })
              clearInterval(valHandler) //销毁定时器 
            })
          }, 800)
          that.data.boxArr.splice(0, that.data.boxArr.length); //清空数组
          console.log(that.data.boxArr, '187')
        } else {
          console.log('没有有数组重复内容：连连看匹配不成功')
          that.setData({
            isListenEnd: false,
            stopSrc: false,
          })
          innerAudioContext.src = '/src/record/false.mp3'
          innerAudioContext.play()
          innerAudioContext.onEnded((res) => {
            console.log('音频结束播放', res)
            that.setData({
              isListenEnd: true,
              stopSrc: true,
            })
          })


          that.setData({
            istrue: false,
            GramOneList: list, //匹配不成功更新数据
          })
          //  console.log(that.data.GramOneList, '666')

          var valHandlers = setTimeout(function () {
            console.log('----')
            list.forEach(item => {
              console.log(item)
              item.status = false
              that.setData({
                istrue: '',
                GramOneList: list, //匹配成功更新数据
              })
              clearInterval(that.valHandlers) //销毁定时器 
              that.data.boxArr.splice(0, that.data.boxArr.length); //清空数组
              //   console.log(that.data.boxArr, '211')
            })
            console.log(that.data.GramOneList, '--sdsds-----')
          }, 800)

        }
      }
    }


  },
  //倒计时
  clickStartBtn: function () {
    console.log("倒计时动画开始")
    var that = this
    var step = that.data.stepText; //定义倒计时
    var scale = that.data.scale; //定义倒计时
    var num = -0.5;
    var decNum = 2 / step / 10
    var start = 1.5 * Math.PI // 开始的弧度
    var end = -0.5 * Math.PI // 结束的弧度
    clearInterval(valHandle)
    function drawArc(endAngle) {
      const ctx = wx.createCanvasContext("bgCanvas")
      ctx.setLineWidth(10 * scale)

      ctx.arc(50 * scale, 75 * scale, 25 * scale, 0, 5 * Math.PI)
      ctx.setStrokeStyle('white')
      ctx.stroke()
      ctx.beginPath()

      ctx.setLineWidth(7 * scale)
      ctx.arc(50 * scale, 75 * scale, 25 * scale, 1.5 * Math.PI, endAngle, true)
      ctx.setStrokeStyle('#FFD734')
      if (that.data.stepText <= 10) {
        if (that.data.stopSrc == true) {
          innerAudioContext.src = '/src/record/err.mp3'
          innerAudioContext.play()
          ctx.setStrokeStyle('#EC2C62')
        } else if (that.data.stopSrc == false) {
          console.log('暂停播放')
        }
        if (that.data.stepText == 0) {
          innerAudioContext.stop()
          clearInterval(valHandle)
          console.log(that.data.numArr.length, '268')
          if (that.data.numArr.length == 6) {
            if (that.data.gameStatus == true) { //如果有下一个游戏
              that.setData({
                main: false,
              })
            } else { //如果为最后一个游戏，则进入下一个任务弹窗
              that.setData({
                main: true,
                bac: true,
              })
            }
          } else {
            console.log('游戏未通关')
            that.setData({
              status: 2,
              backdrop: true, //打开弹窗
              core: false,
              over: true, //游戏失败弹窗
            })
            tool.statistics(app.globalData.openId, app.globalData.moduleId, 2, 1, 2)
          }
        }
        if (that.data.ismaintwo) {
          innerAudioContext.stop()
        }
      }

      ctx.stroke()
      ctx.draw()
    }

    valHandle = setInterval(function () {

      that.setData({
        stepText: parseInt(step)
      })
      step = (step - 0.1).toFixed(1)

      num += decNum
      drawArc(num * Math.PI)
      //   drawArc(start, end);
      if (step <= 0) {
        clearInterval(valHandle) //销毁定时器
      }
      if (that.data.ismaintwo || that.data.bac) {
        clearInterval(valHandle)
      }

    }, 100)
  },
  //结束游戏
  endTask() {
    let that = this
    clearInterval(valHandle) //销毁定时器
    that.endTip.showPopup();
    that.setData({
      backdrop2: true,
      backdrop: true,
      ismaintwo: false,
      core: false,
      stepText: that.data.stepText,
    })
  },
  //确定
  confirm() {
    var that = this
    clearInterval(valHandle)//清除计时
    innerAudioContext.stop()//暂停音频
    tool.statistics(app.globalData.openId, app.globalData.moduleId, 2, 1, 1)
    wx.redirectTo({
      url: '../../../../pages/indexPackage/courseList/courseList',
    })

  },
  //取消
  cancal() {
    let that = this
    that.endTip.hidePopup();
    that.setData({
      backdrop: false,
      backdrop2: false,
      core: true,
      stepText: that.data.stepText

    })
    that.clickStartBtn(that.data.stepText)
  },
  //重新挑战
  track() {
    let that = this
    console.log('222')

    that.setData({
      over: false,
      backdrop: false,
      core: true,
      stepText: 60000,
      numArr: []
    })

    that.GramOneList()
    that.clickStartBtn()

  },
  //休息一下
  restTime() {
    var that = this
    that.unlockLevels(2)
  },
  //休息一下
  rest() {
    console.log(1111)
     
    
    if(app.globalData.addId == 0){
       app.globalData.addId = 1
       
      wx.redirectTo({
        url: '../../../../pages/indexPackage/courseList/courseList?addId='+ 1,
      })
    }else{
      console.log('走缓存处理')
      wx.getStorage({
        key: 'removes',
        success: (res) => {
          console.log(res.data)
          if(res.data){
            console.log('426')
            wx.redirectTo({
              url: '../../../../pages/indexPackage/courseList/courseList?addId=' + 2,
            })
          }
        },
    
      })
    }
 
        


  },
  //下一个游戏
  go_game() {
    let that = this
    console.log(that.data.gameStatus, '******************')

    if (that.data.gameStatus.GameTwo == true) {
      wx.navigateTo({
          url: '/pages/gamePackage/pages/gameWordspell/gameWordspell',
      })
      return
    }else {
      that.unlockLevels(1)
    }
  },
  gotoTask: function () {
    var that = this
    that.unlockLevels(1)
  },
  //解锁
  unlockLevels: function (type) {
    var that = this
    var dataDic = {
      SubtitleId: 3,
      ModuleId: app.globalData.moduleId,
      OpenId: app.globalData.openId
    };

    api.methodBasicEnglish_Unlock({
      dataDic: dataDic,
      success: function (res) {
        console.log('解锁成功', res)
        if (type == 1) {
          that.getTaskStatus()
        } else if (type == 2) {

          
          if(app.globalData.addId == 0){
            app.globalData.addId = 1
            
           wx.reLaunch({
             url: '../../../../pages/indexPackage/courseList/courseList?addId='+ 1,
           })
         }else{
           console.log('走缓存处理')
           wx.getStorage({
             key: 'removes',
             success: (res) => {
               console.log(res.data)
               if(res.data){
                 console.log('426')
                 wx.reLaunch({
                   url: '../../../../pages/indexPackage/courseList/courseList?addId=' + 2,
                 })
               }
             },
         
           })
         }
        }

      },
      fail: function (err) {
        console.log('解锁失败', err)
      }
    })

  },
  //获取任务状态
  getTaskStatus: function () {
    var that = this
    var dataDic = {
      ModuleId: app.globalData.moduleId,
    };
    api.methodBasicEnglish_GetTask({
      dataDic: dataDic,
      success: function (res) {
        console.log('数据请求成功', res)
        app.globalData.taskStatus = res.data.data
        if (res.data.data.TaskOne == true) {
          wx.reLaunch({
            url: '/pages/taskPackage/pages/taskOne/taskOne',
          })
          return
        } else if (res.data.data.TaskTwo == true) {
          wx.reLaunch({
            url: '/pages/taskPackage/pages/taskTwo/taskTwo',
          })
          return
        } else if (res.data.data.TaskThree == true) {
          wx.reLaunch({
            url: '/pages/taskPackage/pages/taskThree/taskThree',
          })
          return
        } else if (res.data.data.TaskFour == true) {
          wx.reLaunch({
            url: '/pages/taskPackage/pages/taskFour/taskFour',
          })
          return
        }
      },
      fail: function (err) {
        console.log('数据请求失败', err)
      }
    })

  },


  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
  },
  onHide:function(){
      innerAudioContext.offEnded()
  },
  onUnload:function(){
      innerAudioContext.offEnded()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
      return {
          path: 'pages/indexPackage/index/index',
          success: function (res) {
              console.log('转发成功', res);
          },
          fail: function (err) {
              console.log('转发失败', err)
          }
      }
  }
})